#
# Copyright (C) [2024] Xingyun Integrated Circuit, Inc.
#
# GreenCode was a private technology asset of Xingyun Integrated Circuit， Inc （Confidential）
# Author: Shawn.Tan
# Date: 2025.10.28
#
# History: Initial Version 2025.10.28
#
#
from base.Sequence import Sequence
from gpgpu.EnvGPGPU import EnvGPGPU
from gpgpu.GenThreadGPGPU import GenThreadGPGPU


# This test generates a virtual address in a different privilege level from
# that in which it is used. The genVA() method should respect the privilege
# level specified rather than the one in which the address was generated.
class MainSequence(Sequence):
    def generate(self, **kargs):
        self.systemCall({"PrivilegeLevel": 1})

        instr = "LD##CALM"
        size = 8

        if self.getGlobalState("AppRegisterWidth") == 32:
            instr = "LW##CALM"
            size = 4

        # Generate a target address for a U Mode instruction from S Mode
        target_addr = self.genVA(Size=size, Align=size, Type="D", PrivilegeLevel=0)

        self.systemCall({"PrivilegeLevel": 0})

        self.genInstruction(instr, {"LSTarget": target_addr})
        self._assertNoPageFault(target_addr)

        # Generate a target address for an S Mode instruction from U Mode
        target_addr = self.genVA(Size=size, Align=size, Type="D", PrivilegeLevel=1)

        self.systemCall({"PrivilegeLevel": 1})

        self.genInstruction(instr, {"LSTarget": target_addr})
        self._assertNoPageFault(target_addr)

    # Fail if a load page fault occurred.
    #
    #  @param aTargetAddr The target address of the previous load instruction.
    def _assertNoPageFault(self, aTargetAddr):
        if self.queryExceptionRecordsCount(13) > 0:
            self.error(
                "A LD instruction targeting 0x%x triggered an unexpected "
                "page fault" % aTargetAddr
            )


MainSequenceClass = MainSequence
GenThreadClass = GenThreadGPGPU
EnvClass = EnvGPGPU
